package com.xc.ksxt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xc.common.object.LayuiTableResponse;
import com.xc.common.object.PageInfo;
import com.xc.common.object.ResponseEntity;
import com.xc.common.tool.CheckRepeat;
import com.xc.common.tool.Helper;
import com.xc.db.tables.*;
import com.xc.ksxt.StringSimilarity;
import com.xc.ksxt.entity.*;
import com.xc.ksxt.service.*;
import com.xc.ksxt.vo.LibQuestionVO;
import com.xc.sys.entity.SysDictEntity;
import com.xc.sys.entity.SysUserEntity;
import com.xc.sys.service.BaseCodeNumberService;
import com.xc.sys.service.SysDictService;
import com.xc.sys.service.SysUserService;
import com.xc.sys.vo.SysUserVO;
import com.xc.word.wordUtil.WordRead;
import com.xc.word.wordUtil.WordReader;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.lang3.StringUtils;

import static org.jooq.impl.DSL.*;

import org.apache.poi.xwpf.usermodel.*;
import org.jetbrains.annotations.NotNull;
import org.jooq.*;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/libQuestion")
@CrossOrigin
public class LibQuestionController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DSLContext dsl;
    @Autowired
    private WordReader wordReader;
    @Autowired
    private WordRead wordRead;
    @Autowired
    private LibQuestionService libQuestionService;
    @Autowired
    private LibChoiceService libChoiceService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ImportRecordService importRecordService;
    @Autowired
    private KnowledgePointService knowledgePointService;
    @Autowired
    private TagService tagService;
    @Autowired
    private PaperService paperService;
    private Tag TAG = Tag.TAG.as("TAG");
    private KnowledgePoint KLP = KnowledgePoint.KNOWLEDGE_POINT.as("KLP");
    private LibQuestion LIBQUESTIONTB = LibQuestion.LIB_QUESTION.as("LIBQUESTIONTB");
    private LibChoice LIBCHOICETB = LibChoice.LIB_CHOICE.as("LIBCHOICETB");
    private Question QUESTION = Question.QUESTION.as("QUESTION");
    @CrossOrigin(origins = "*", allowedHeaders = {"*"}, methods = {RequestMethod.GET})
    @RequestMapping({"/getPageList"})
    public LayuiTableResponse<LibQuestionVO> getPageList(HttpServletRequest request) {
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        String field = request.getParameter("field");
        String order = request.getParameter("order");
        String recordId = request.getParameter("recordId");
        Condition cond = null;
        if(recordId==null){
            cond = LIBQUESTIONTB.DEL_FLAG.notEqual(-1);
        }else{
            cond = DSL.trueCondition();
        }
        String name = request.getParameter("name");
        String text = request.getParameter("text");
        String lg = request.getParameter("lg");
        String difficulty = request.getParameter("difficulty");
        String questionType = request.getParameter("questionType");
        String contentType = request.getParameter("contentType");

        String source = request.getParameter("source");
        String pianId = request.getParameter("pianId");
        String chapterId = request.getParameter("chapterId");
        String jieId = request.getParameter("jieId");
        String excludePaperIds = request.getParameter("excludePaperIds");
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer page = Integer.valueOf(request.getParameter("page"));
        if (StringUtils.isNotBlank(recordId)) {
        	cond = cond.and(LIBQUESTIONTB.RECORD_ID.eq( Integer.valueOf(recordId) ));
        }
        if (StringUtils.isNotBlank(source)) {
        	cond = cond.and(LIBQUESTIONTB.SOURCE.eq( Integer.valueOf(source) ));
        }
        if (StringUtils.isNotBlank(lg)) {
        	cond = cond.and(LIBQUESTIONTB.LG.eq( Integer.valueOf(lg) ));
        }
        if (StringUtils.isNotBlank(difficulty)) {
        	cond = cond.and(LIBQUESTIONTB.DIFFICULTY.eq( Integer.valueOf(difficulty) ));
        }
        if (StringUtils.isNotBlank(questionType)) {
        	cond = cond.and(LIBQUESTIONTB.QUESTION_TYPE.eq( Integer.valueOf(questionType) ));
        }
        if (StringUtils.isNotBlank(contentType)) {
        	cond = cond.and(LIBQUESTIONTB.CONTENT_TYPE.eq( Integer.valueOf(contentType) ));
        }
        if (StringUtils.isNotBlank(name)) {
        	cond = cond.and(LIBQUESTIONTB.TEXT.like( "%" + name + "%" ));
        }
        if (StringUtils.isNotBlank(text)) {
        	cond = cond.and(LIBQUESTIONTB.TEXT.like("%"+text+"%"));
        }
        if (StringUtils.isNotBlank(jieId)) {
        	cond = cond.and(LIBQUESTIONTB.JIE_ID.eq(Integer.valueOf(jieId)));
        }else if(StringUtils.isNotBlank(chapterId)){
            cond = cond.and(LIBQUESTIONTB.CHAPTER_ID.eq(Long.valueOf(chapterId)));
        }else if(StringUtils.isNotBlank(pianId)){
            cond = cond.and(LIBQUESTIONTB.PIAN_ID.eq(Long.valueOf(pianId)));
        }
        if (StringUtils.isNotBlank(excludePaperIds)) {
            Long[] arr = Helper.str2longArr(excludePaperIds);
        	cond = cond.and(notExists(selectOne().from(QUESTION).where(QUESTION.PAPER_ID.in(arr)).and(LIBQUESTIONTB.ID.eq(QUESTION.LIB_QUESTION_ID))))
                    .and(DSL.or(LIBQUESTIONTB.PAPER_ID.notIn(arr),LIBQUESTIONTB.PAPER_ID.isNull()));
        }
        SortField<?>[] orderby = new SortField[]{LIBQUESTIONTB.CODE.desc(),LIBQUESTIONTB.CREATE_TIME.desc()};
        if(order!=null){
            if(order.equals("desc")){
                orderby = new SortField[]{field(field).desc()};
            }else{
                orderby = new SortField[]{field(field).asc()};
            }

        }
        String sortField = request.getParameter("sortField");
        if(sortField!=null){
            orderby = new SortField[]{field("orderno").asc()};
        }
        request.getSession().setAttribute("LIBQUESTIONCOND",cond);
        request.getSession().setAttribute("LIBQUESTIONORDERBY",orderby);
        Long count = libQuestionService.count(cond);
        ltr.setCount(count);
        PageInfo<LibQuestionEntity> pageInfo = new PageInfo<>(limit, page);
        Result<Record> list = libQuestionService.select(cond, pageInfo,orderby);
        List<LibQuestionVO> libQuestionEntityList = list.into(LibQuestionVO.class);
        for (LibQuestionVO libQuestionEntity : libQuestionEntityList){
            setTxt(libQuestionEntity);
        }

        ltr.setData(libQuestionEntityList);
        return ltr;
    }
    @RequestMapping({"/selectList"})
    public LayuiTableResponse<LibQuestionVO> selectList(HttpServletRequest request) {
        String joinid2 = request.getParameter("joinid2");
        String nums = request.getParameter("num");
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        Condition cond = (Condition)request.getSession().getAttribute("LIBQUESTIONCOND");
        SortField<?>[] orderby = (SortField<?>[])request.getSession().getAttribute("LIBQUESTIONORDERBY");
        Result<Record> records = libQuestionService.select(cond, null,orderby);
        List<LibQuestionVO> list = records.into(LibQuestionVO.class);
        List<LibQuestionVO> list2 = new ArrayList<>();
        Set<String> idset = new HashSet<>();
        String joinid = request.getParameter("joinid");
        List<LibQuestionVO> pList = LibQuestionService.JOINCACHE.getIfPresent(joinid);
        if(pList!=null){
            for (LibQuestionVO v : pList) {
                idset.add(v.getId());
            }
        }
        if(nums!=null){//抽题
            int num = Integer.valueOf(nums);
            if(records.size()<num){
                ltr.setCode(201);
                ltr.setData(list2);
                ltr.setMsg("题数不够");
                return ltr;
            }else if(records.size()==num){
                list2.addAll(list);
            }else{
                HashSet<String> repeatSet = new HashSet();
                while(true){
                    double pom = Math.random();
                    int n = (int)(pom * list.size());
                    LibQuestionVO te = list.get(n);
                    if(repeatSet.contains(te.getId())){
                        continue;
                    }
                    if(idset.contains(te.getId())){
                        continue;
                    }
                    repeatSet.add(te.getId());
                    list2.add(te);
                    if(list2.size()>=num){
                        break;
                    }
                }
            }

            for (LibQuestionVO libQuestionEntity : list2){
                setTxt(libQuestionEntity);
            }
            ltr.setData(list2);
            LibQuestionService.JOINCACHE2.put(joinid2,list2);
        }else{
            if(pList!=null){
                List<LibQuestionVO> data = new ArrayList<>();
                for (LibQuestionVO ev : list){
                    if(idset.contains(ev.getId())){
                        continue;
                    }
                    setTxt(ev);
                    data.add(ev);
                }
                ltr.setData(data);
            }else {
                for (LibQuestionVO ev : list){
                    setTxt(ev);
                }
                ltr.setData(list);
            }
        }

        return ltr;
    }
    //组卷时添加选择的试题
    @RequestMapping({"/addJoined"})
    @Transactional
    public JSONObject addJoined(HttpServletRequest request) {
        SysUserEntity me = Helper.getMe(request);
        JSONObject obj = new JSONObject();
        if(me==null){
            obj.put("code",1);
            obj.put("msg","操作超时");
            return obj;
        }
        obj.put("code",0);
        obj.put("msg","加入队列成功");
        String joinid = request.getParameter("joinid");
        String joinid2 = request.getParameter("joinid2");
        if(joinid2==null){
            obj.put("code",1);
            obj.put("msg","请抽题");
            return obj;
        }
        List<LibQuestionVO> joinedList = LibQuestionService.JOINCACHE.getIfPresent(joinid);
        List<LibQuestionVO> joinedList2 = LibQuestionService.JOINCACHE2.getIfPresent(joinid2);
        if(joinedList2==null){
            obj.put("code",1);
            obj.put("msg","请抽题");
            return obj;
        }

        if(joinedList==null){
            PaperEntity paperEntity = PaperService.getFromCaches(joinid);
            if(paperEntity==null){
                paperEntity = new PaperEntity();
                paperEntity.setState(1);
                paperEntity.setId(joinid);
                paperEntity.setName("待命名");
                paperEntity.setCreateTime(LocalDateTime.now());
                paperEntity.setCreateUserId(me.getId());
                String code = BaseCodeNumberService.genCode("paper-code", 4);
                paperEntity.setCode(code);
                paperService.insert(paperEntity);
            }
            joinedList = new ArrayList<>();
        }

        joinedList.addAll(joinedList2);
        LibQuestionService.JOINCACHE.put(joinid,joinedList);
        return obj;
    }
    @RequestMapping({"/addJoined2"})
    @Transactional
    public JSONObject addJoined2(HttpServletRequest request) {
        SysUserEntity me = Helper.getMe(request);
        JSONObject obj = new JSONObject();
        if(me==null){
            obj.put("code",1);
            obj.put("msg","操作超时");
            return obj;
        }
        obj.put("code",0);
        obj.put("msg","加入队列成功");
        String ids = request.getParameter("id");
        String[] idarr = ids.split(",");
        String joinid = request.getParameter("joinid");
        List<LibQuestionVO> joinedList = LibQuestionService.JOINCACHE.getIfPresent(joinid);

        if(joinedList==null){
            PaperEntity paperEntity = PaperService.getFromCaches(joinid);
            if(paperEntity==null){
                paperEntity = new PaperEntity();
                paperEntity.setState(1);
                paperEntity.setId(joinid);
                paperEntity.setName("待命名");
                paperEntity.setCreateTime(LocalDateTime.now());
                paperEntity.setCreateUserId(me.getId());
                String code = BaseCodeNumberService.genCode("paper-code", 4);
                paperEntity.setCode(code);
                paperService.insert(paperEntity);
            }
            joinedList = new ArrayList<>();
        }
        for(int i=0;i<idarr.length;i++) {
            String id = idarr[i];
            boolean exists = false;
            for (LibQuestionVO v : joinedList) {
                if(v.getId().equals(id)){
                    exists = true;
                }
            }
            if(!exists){
                LibQuestionVO v = libQuestionService.getRecordById(id).into(LibQuestionVO.class);
                setTxt(v);
                joinedList.add(v);
            }
        }

        LibQuestionService.JOINCACHE.put(joinid,joinedList);
        return obj;
    }
    //查看组卷结果
    @RequestMapping({"/getJoinResult"})
    public LayuiTableResponse<LibQuestionVO> getJoinResult(HttpServletRequest request) {
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        String joinid = request.getParameter("joinid");
        List<LibQuestionVO> list = LibQuestionService.JOINCACHE.getIfPresent(joinid);
        if(list==null){
            list = new ArrayList<>();
        }
        ltr.setData(list);

        return ltr;
    }
    @RequestMapping({"/deleteJoined"})
    public LayuiTableResponse<LibQuestionVO> deleteJoined(@RequestBody Map<String,String> params) {
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        String joinid = params.get("joinid");
        String ids = params.get("ids");
        ltr.setCode(1);
        ltr.setMsg("删除失败");
        List<LibQuestionVO> list = LibQuestionService.JOINCACHE.getIfPresent(joinid);
        List<LibQuestionVO> list2 = new ArrayList<>();

        for (LibQuestionVO v : list) {
            if(ids.indexOf(v.getId())==-1){
                list2.add(v);
            }
        }
        LibQuestionService.JOINCACHE.put(joinid,list2);
        ltr.setData(list2);
        ltr.setCode(0);
        ltr.setMsg("删除成功");
        return ltr;
    }
//1326762
    private void setTxt(LibQuestionVO libQuestionEntity) {
        if(libQuestionEntity.getCreateUserId()!=null){
            SysUserVO user = SysUserService.getFrameCaches(libQuestionEntity.getCreateUserId());
            libQuestionEntity.setCreateUserName(user==null?"":user.getName());
        }
        SysDictEntity dict = SysDictService.getFromCaches("question-type," + libQuestionEntity.getQuestionType());
        libQuestionEntity.setQuestionTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("content-type," + libQuestionEntity.getContentType());
        libQuestionEntity.setContentTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("paper-lg," + libQuestionEntity.getLg());
        libQuestionEntity.setLgTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("question-difficulty," + libQuestionEntity.getDifficulty());
        libQuestionEntity.setDifficultyTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("test-phase," + libQuestionEntity.getTestPhase());
        libQuestionEntity.setTestPhaseTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("rvalid-state," + libQuestionEntity.getState());
        libQuestionEntity.setStateTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("test-type," + libQuestionEntity.getTestType());
        libQuestionEntity.setTestTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("paper-type," + libQuestionEntity.getPaperType());
        libQuestionEntity.setPaperTypeTxt(dict==null?"":dict.getName());
        dict = SysDictService.getFromCaches("repeatable," + libQuestionEntity.getIgnoreRepeat());
        libQuestionEntity.setIgnoreRepeatTxt(dict==null?"":dict.getName());
        libQuestionEntity.setText(libQuestionEntity.getText().replace("<br>",""));
        if(libQuestionEntity.getQuestionType()<=3){
            List<LibChoiceEntity> choiceList = libChoiceService.select(LIBCHOICETB.LIB_QUESTION_ID.eq(Long.valueOf(libQuestionEntity.getId())).and(LIBCHOICETB.DEL_FLAG.eq(1)), LIBCHOICETB.INDEX_LETTER.asc());
            StringBuilder buf = new StringBuilder();
            for (LibChoiceEntity libChoiceEntity : choiceList) {
                buf.append(libChoiceEntity.getIndexLetter() + "." + libChoiceEntity.getText());
                if(!libChoiceEntity.getText().endsWith("<br>")){
                    buf.append("<br>");
                }
            }
            if(libQuestionEntity.getText().length()<24){
                libQuestionEntity.setText2(libQuestionEntity.getText() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>" + buf);
            }else{
                libQuestionEntity.setText2(libQuestionEntity.getText() + "<br>" + buf);
            }

        }else {
            libQuestionEntity.setText2(libQuestionEntity.getText());
        }

        if(libQuestionEntity.getPianId()!=null){
            PianEntity pian = PianService.getFromCaches(libQuestionEntity.getPianId());
            libQuestionEntity.setPianName(pian==null?"":pian.getName());
        }
        if(libQuestionEntity.getJieId()!=null){
            JieEntity jie = JieService.getFromCaches(libQuestionEntity.getJieId());
            libQuestionEntity.setJieName(jie==null?"":jie.getName());
        }
        if(libQuestionEntity.getChapterId()!=null){
            Result<Record1<Object>> r = dsl.select(field("name")).from(table("chapter")).where(field("id").eq(libQuestionEntity.getChapterId())).fetch();
            if(r.size()!=0){
                libQuestionEntity.setChapterName(r.get(0).get(0,String.class));
            }
        }
        if(libQuestionEntity.getCollegeId()!=null){
            Result<Record1<Object>> r = dsl.select(field("name")).from(table("college")).where(field("id").eq(libQuestionEntity.getCollegeId())).fetch();
            if(r.size()!=0){
                libQuestionEntity.setCollegeName(r.get(0).get(0,String.class));
            }
        }
        if(libQuestionEntity.getTag()!=null&&!libQuestionEntity.getTag().isEmpty()){
            Integer[] iTagId = Helper.str2integerArr(libQuestionEntity.getTag());
            List<TagEntity> tags = tagService.select(TAG.ID.in(iTagId));
            List<String> names = tags.stream().map(v -> {
                return v.getName();
            }).collect(Collectors.toList());
            libQuestionEntity.setTagName(StringUtils.join(names,","));
        }
        if(libQuestionEntity.getKnowledge()!=null&&!libQuestionEntity.getKnowledge().isEmpty()){
            Long[] iTagId = Helper.str2longArr(libQuestionEntity.getKnowledge());
            List<KnowledgePointEntity> tags = knowledgePointService.select(KLP.ID.in(iTagId));
            List<String> names = tags.stream().map(v -> {
                return v.getName();
            }).collect(Collectors.toList());
            libQuestionEntity.setKnowledgeName(StringUtils.join(names,","));
        }
        if(libQuestionEntity.getKnowledge()!=null&&!libQuestionEntity.getKnowledge().isEmpty()){
            Long[] iTagId = Helper.str2longArr(libQuestionEntity.getKnowledge());
            List<KnowledgePointEntity> tags = knowledgePointService.select(KLP.ID.in(iTagId));
            List<String> names = tags.stream().map(v -> {
                return v.getName();
            }).collect(Collectors.toList());
            libQuestionEntity.setKnowledgeName(StringUtils.join(names,","));
        }
        if(libQuestionEntity.getMajorId()!=null){
            MajorEntity majorEntity = MajorService.getFromCaches(libQuestionEntity.getMajorId());
            libQuestionEntity.setMajorName(majorEntity==null?"":majorEntity.getName());
        }
    }

    @RequestMapping({"/getById"})
    public LibQuestionVO getById(Long id) {
        Record r = libQuestionService.getRecordById(id);
        if(r.size()==0){
            return null;
        }
        LibQuestionVO entity = r.into(LibQuestionVO.class);
        setTxt(entity);
        return entity;
    }
    
    @RequestMapping({"/getMaxOrderno"})
    public Integer getMaxOrderno() {
    	Integer maxOrderno = dsl.select(ifnull(max(LIBQUESTIONTB.ORDERNO), 0)).from(LIBQUESTIONTB).fetchOneInto(Integer.class);
    	return maxOrderno;
    }

    @RequestMapping({"/save"})
    public ResponseEntity<LibQuestionEntity> save(@RequestBody HashMap<String,String> params) {
    	ResponseEntity<LibQuestionEntity> res = new ResponseEntity<>();
    	LibQuestionEntity libQuestionEntity = Helper.map2Bean(new LibQuestionEntity(), params);
        if(libQuestionEntity.getCode()==0){
            libQuestionEntity.setCode(null);
        }
        if(libQuestionEntity.getCode()==null){
            @NotNull Result<Record1<Integer>> result = dsl.select(LIBQUESTIONTB.CODE).from(LIBQUESTIONTB).fetch();
            if(result.size()==0){
                libQuestionEntity.setCode(1);
            }else{
                Set<String> codeSet = new HashSet<>();
                for (Record1<Integer> rd : result) {
                    codeSet.add(rd.get(0,String.class));
                }
                int code = 2;
                while(true){
                    if(!codeSet.contains(code+"")){
                        break;
                    }
                    code++;
                }

                libQuestionEntity.setCode(code);
            }
        }
        String text = libQuestionEntity.getText();
        if(text.startsWith("<p>")){
            text = text.substring(3);
            int end = text.lastIndexOf("</p>");
            text = text.substring(0,end);
        }
        text = changeImgBase642File(text);
        libQuestionEntity.setText(text);
        String answerText = libQuestionEntity.getAnswerText();
        if(answerText.startsWith("<p>")){
            answerText = answerText.substring(3);
            int end = answerText.lastIndexOf("</p>");
            answerText = answerText.substring(0,end);
        }
        answerText = changeImgBase642File(answerText);
        libQuestionEntity.setAnswerText(answerText);
        String analysis = libQuestionEntity.getAnalysis();
        if(analysis.startsWith("<p>")){
            analysis = analysis.substring(3);
            int end = analysis.lastIndexOf("</p>");
            analysis = analysis.substring(0,end);
        }
        analysis = changeImgBase642File(analysis);
        libQuestionEntity.setAnalysis(analysis);
        libQuestionService.save(libQuestionEntity);
        res.setData(libQuestionEntity);
        return res;
    }
    private String changeImgBase642File(String text){
        if(text.indexOf("src=\"data:image/png;base64,")==-1){
            return text;
        }
        String[] texts = text.split("src=\"data:image/png;base64,");
        String base64 = StringUtils.substringBefore(texts[1],"\"");
        byte[] bytes = Base64.getDecoder().decode(base64);
        String imgUrl = "";
        try {
            imgUrl = WordRead.getImageUrl(bytes,"123.png");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        text = texts[0] + "src=\"" + imgUrl + "\"" + StringUtils.substringAfter(texts[1],"\"");;
        return text;
    }
    @RequestMapping({"/updateOrderno"})
    public ResponseEntity<LibQuestionEntity> updateOrderno(@RequestBody HashMap<String,String> params) {
        Long id = Long.valueOf(params.get("id"));
        Integer orderno = Integer.valueOf(params.get("orderno"));
        ResponseEntity<LibQuestionEntity> res = new ResponseEntity<>();
        LibQuestionEntity lq = libQuestionService.getEntityById(id);
        lq.setOrderno(orderno);
        libQuestionService.update(lq);
        return res;
    }

    @RequestMapping({"/delete"})
    public LayuiTableResponse<LibQuestionEntity> delete(@RequestBody Map<String,String> params) {
        String ids = params.get("ids");
        Long[] idarr = Helper.str2longArr(ids);
        LayuiTableResponse<LibQuestionEntity> ltr = new LayuiTableResponse<>();
        for (Long id : idarr) {
            LibQuestionEntity m = libQuestionService.getEntityById(id);
            m.setDelFlag(-1);
            libQuestionService.update(m);
        }
        return ltr;
    }
    @RequestMapping({"/ignore"})
    public LayuiTableResponse<LibQuestionEntity> ignore(@RequestBody Map<String,String> params) {
        String ids = params.get("ids");
        Long[] idarr = Helper.str2longArr(ids);
        LayuiTableResponse<LibQuestionEntity> ltr = new LayuiTableResponse<>();
        for (Long id : idarr) {
            LibQuestionEntity m = libQuestionService.getEntityById(id);
            m.setIgnoreRepeat(2);
            libQuestionService.update(m);
        }
        return ltr;
    }
    @RequestMapping({"/queryTheSimilarList"})
    public LayuiTableResponse<LibQuestionVO> queryTheSimilarList() {
        String id = request.getParameter("id");
        LibQuestionEntity lq = libQuestionService.getEntityById(Long.valueOf(id));
        SelectConditionStep<Record2<Long, String>> r = dsl.select(LIBQUESTIONTB.ID, LIBQUESTIONTB.TEXT).from(LIBQUESTIONTB).where(LIBQUESTIONTB.LIB_ID.eq(lq.getLibId()).and(LIBQUESTIONTB.ID.notEqual(Long.valueOf(id))));
        List<Long> ids = new ArrayList<>();
        for (Record2<Long, String> record : r) {
            boolean isSimilar = CheckRepeat.checkTheDuplicate(lq.getText(), record.get(1,String.class), 0.7);
            if(isSimilar){
                ids.add(record.get(0,Long.class));
            }
        }
        List<LibQuestionVO> list = libQuestionService.selectVO(LIBQUESTIONTB.ID.in(ids), LIBQUESTIONTB.ORDERNO.asc());
        for (LibQuestionVO libQuestionEntity : list){
            setTxt(libQuestionEntity);
        }
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        ltr.setData(list);
        return ltr;
    }
    @RequestMapping({"/querySimilarList"})
    public LayuiTableResponse<LibQuestionVO> querySimilarList() {
//        long time1 = System.currentTimeMillis();
        LayuiTableResponse<LibQuestionVO> ltr = new LayuiTableResponse<>();
        HashMap<Integer,Set<Long>> matchMap = new HashMap<>();
        SelectConditionStep<Record2<Long, String>> r = dsl.select(LIBQUESTIONTB.ID, LIBQUESTIONTB.TEXT).from(LIBQUESTIONTB).where(LIBQUESTIONTB.IGNORE_REPEAT.eq(1));
        Map<Long,String> map = new LinkedMap<>();
        for (Record2<Long, String> record : r) {
            map.put(record.get(0,Long.class),record.get(1,String.class));
        }
//        long time2 = System.currentTimeMillis();
//        System.out.println("第一段："+ ((time2-time1)/1000));
        int n = 1;
        int a = 0;
        Set<Long> repeatSet = new HashSet();
        for (Record2<Long, String> record : r) {
//            a++;
//            if(a<=106||a>=110){
//                continue;
//            }

            matchMap.put(n,new HashSet<>());
            Set<Long> keys = map.keySet();
            Long id = record.get(0,Long.class);
            if(repeatSet.contains(id)){//已判断过
                continue;
            }
            String text1 = record.get(1,String.class);
//            System.out.println("text1 ============ " + text1);

            for (Long key : keys) {
                if(id.longValue()==key){
                    continue;
                }
                String text = map.get(key);
                int len = Math.abs(text1.length()-text.length());
                if(len>11){
                    continue;
                }
                double degree = StringSimilarity.levenshteinSimilarity(text1, text);

                if(degree>96){
//                    System.out.println("text = " + text);
//                    System.out.println("degree = " + degree);
                    Set<Long> set = matchMap.get(n);
                    set.add(id);
                    set.add(key);
                    repeatSet.add(key);
                }

            }
            n++;
        }
//        long time3 = System.currentTimeMillis();
//        System.out.println("第2段："+ ((time3-time2)/1000));
        Set<Integer> matchKeySet = matchMap.keySet();
        Set<Integer> sortedSet = new TreeSet<>(matchKeySet);
        Set ids = new HashSet();
        for (Integer i : matchKeySet) {
            Set<Long> idSet = matchMap.get(i);
            ids.addAll(idSet);
        }
        List<LibQuestionVO> list = libQuestionService.selectVO(LIBQUESTIONTB.ID.in(ids), LIBQUESTIONTB.ORDERNO.asc());
        if(list==null){
            list = new ArrayList<>();
        }else{

            HashMap<Integer,List<LibQuestionVO>> llist = new HashMap<>();
            for (Integer i : matchKeySet) {
                llist.put(i,new ArrayList<>());
            }
            for (LibQuestionVO libQuestionEntity : list){
                long id = Long.valueOf(libQuestionEntity.getId());
                for (Integer i : matchKeySet) {
                    boolean ok = false;
                    Set<Long> set = matchMap.get(i);
                    List<LibQuestionVO> entitys = llist.get(i);
                    for (long l : set) {
                        if(id==l){
                            libQuestionEntity.setText(i + ": "+libQuestionEntity.getText());
                            entitys.add(libQuestionEntity);
                            ok = true;
                            break;
                        }
                    }

                    if(ok){

                        break;
                    }
                }
                setTxt(libQuestionEntity);
            }
            list = new ArrayList<>();
            for (Integer i : sortedSet) {
                List<LibQuestionVO> entitys = llist.get(i);
                list.addAll(entitys);
            }
        }
        ltr.setCount(Long.valueOf(list.size()));
        ltr.setData(list);
        return ltr;
    }
    @RequestMapping ("/importWord")
    @Transactional
    public JSONObject importWord(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        JSONObject res = new JSONObject();
        SysUserEntity me = Helper.getMe(request);
        Long majorId = Long.valueOf(request.getParameter("majorId"));
        String collegeId = request.getParameter("collegeId");
        String gradeYear = request.getParameter("gradeYear");
        String testType = request.getParameter("testType");
        String testPhase = request.getParameter("testPhase");
        String paperType = request.getParameter("paperType");
        String howlong = request.getParameter("howlong");
        String lg = request.getParameter("lg");
        String grade = request.getParameter("grade");
        String semester = request.getParameter("semester");
        String studentType = request.getParameter("studentType");
        String categoryId = String.valueOf(request.getParameter("categoryId"));
        Integer recordId = Integer.valueOf(request.getParameter("recordId"));
        ImportRecordEntity ire = new ImportRecordEntity();
        if(recordId!=-1){
            ire = importRecordService.getEntityById(recordId);
            dsl.delete(table("lib_question")).where(field("record_id").eq(recordId)).execute();
            dsl.delete(table("lib_choice")).where(field("record_id").eq(recordId)).execute();
        }else{
            ire.setCategoryId(categoryId);
            ire.setCode(Helper.genCode(""));
            ire.setCreateTime(LocalDateTime.now());
            ire.setCreateUserId(me.getId());
            ire.setState(1);
            ire.setMajorId(majorId + "");
            ire.setCollegeId(collegeId);
            ire.setGradeYear(gradeYear);
            ire.setGrade(grade);
            ire.setTestPhase(Integer.valueOf(testPhase));
            ire.setStudentType(Integer.valueOf(studentType));
            ire.setSemester(Integer.valueOf(semester));
            ire.setPaperType(Integer.valueOf(paperType));
            ire.setTestType(Integer.valueOf(testType));
            ire.setHowlong(howlong==null?null:Integer.valueOf(howlong));
            ire.setLg(Integer.valueOf(lg));
            importRecordService.save(ire);
        }

        List<ChapterEntity> categoryList = chapterService.select(DSL.trueCondition());
        HashMap<String,ChapterEntity> chapterMap = new HashMap<>();
        for (ChapterEntity chapterEntity : categoryList) {
            String cname = StringUtils.deleteWhitespace(chapterEntity.getName());
            chapterMap.put(cname,chapterEntity);
        }
        XWPFDocument docx = new XWPFDocument(file.getInputStream());
        List<IBodyElement> bes = docx.getBodyElements();
        res = wordRead.readWordImgToHtml(docx,ire,collegeId,majorId,gradeYear,grade,categoryId,testPhase,semester,lg,testType,paperType,studentType,howlong,chapterMap,me);

        return res;
    }
/*    private static String getParagraphText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            //System.out.println("按了回车（新段落）");
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
//		if (runText.length() > 0) {
//			runText.append("，对齐方式：").append(paragraph.getAlignment().name());
//			System.out.println(runText);
//		}
        return runText.toString();
    }*/
    /**
     * 获取表格内容（ docx后缀名的Word）
     * @param table
     */
/*    private static String getTabelText(XWPFTable table) {
        String result="";
        //获取表格数据行
        List<XWPFTableRow> rows = table.getRows();
        if(rows.size()>0){
            //遍历
            for (int i=0;i<rows.size();i++) {
                XWPFTableRow row = rows.get(i);
                //获取每行的数据列
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    String cellText="";
                    // 简单获取内容（简单方式是不能获取字体对齐方式的）
                    // System.out.println(cell.getText());
                    // 一个单元格可以理解为一个word文档，单元格里也可以加段落与表格
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        cellText+=getParagraphText(paragraph);
                    }
                    result+=cellText;
                }
            }
        }
        return result;
    }*/


/*    private void getDocNodeList(Node node){
        if(node.getNodeName().equals("w:bookmarkStart")){
            System.out.println("开始");
        }else if(node.getNodeName().equals("w:bookmarkEnd")){
            System.out.println("结束");
        }else{
            NodeList nodeList = node.getChildNodes();
            for (int n = 0; n < nodeList.getLength(); n++) {
                Node childNode = nodeList.item(n);

                if("#text".equals(childNode.getNodeName())){
                    System.out.println("childNode.getPrefix() = " + childNode.getPrefix());
                    System.out.println("childNode.getNodeValue() = " + childNode.getNodeValue());
                }

                getDocNodeList(childNode);
            }
        }
    }*/

}
